# 加载数据源
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# import sys
# print("Python version: {}".format(sys.version))
# import pandas as pd
# print("pandas version: {}".format(pd.__version__))
# import matplotlib
# print("matplotlib version: {}".format(matplotlib.__version__))
# import numpy as np
# print("NumPy version: {}".format(np.__version__))
# import scipy as sp
# print("SciPy version: {}".format(sp.__version__))
# import IPython
# print("IPython version: {}".format(IPython.__version__))
# import sklearn
# print("scikit-learn version: {}".format(sklearn.__version__))


# 1.切分train data and test data
# 拆分数据可以便于训练模型和检查模型的正确性
iris_dataset = load_iris()
x_train, x_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state=0)

# print("x_train shape： {}".format(x_train.shape))
# print("y_train shape： {}".format(y_train.shape))
# print("x_test shape: {}".format(x_test.shape))
# print("y_test shape: {}".format(y_test.shape))

# 2.训练之前检查数据的正确性，确保数据在同一维度，比如单位
# 通过观察数据来检查
# iris_dataframe = pd.DataFrame(x_train, columns=iris_dataset.feature_names)
# sns.pairplot(iris_dataframe)
# 显示图表
# plt.title('iris_dataframe')
# plt.show()

# 3.训练模型，使用k-nearest neighbors算法
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x_train, y_train)

# 4.预测新花朵
x_new = np.array([[5,2.9,1,0.2]])
print("x_new: {}".format(x_new.shape))

prediction = knn.predict(x_new)
print("prediction:{}".format(prediction))
print("prediction target name:{}".format(iris_dataset.target_names[prediction]))

# 5.测试模型正确性
y_pred = knn.predict(x_test)
print("x_pred:{}".format(y_pred))
print("test set score:{:.2f}".format(np.mean(y_pred == y_test)))
print("knn set score:{:.2f}".format(knn.score(x_test, y_test)))